//
//  SCContactViewController.m
//  SmartCall
//
//  Created by Maximus on 1/6/14.
//  Copyright (c) 2014 Nguyen Xuan Hoc. All rights reserved.
//

#import "SCContactViewController.h"
#import "Person.h"


@interface SCContactViewController (){
    IBOutlet UITableView *tableView;
}
@property (nonatomic, strong)NSMutableArray *contactArray;
@property (nonatomic, strong)NSDictionary *contactAlphabeta;

@end

@implementation SCContactViewController
@synthesize contactArray;
@synthesize contactAlphabeta;



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    contactArray = [[NSMutableArray alloc]init];
    [self getPersonOutOfAddressBook];
    contactAlphabeta = [self alphabetizeContacts:contactArray];
    
}

- (void)getPersonOutOfAddressBook{
    CFErrorRef error = NULL;
    
    ABAddressBookRef addressBook =
    ABAddressBookCreateWithOptions(NULL, &error);
    if (addressBook != nil)
    {
        NSLog(@"Succesful.");
        
        NSArray *allContacts = (__bridge_transfer NSArray
                                *)ABAddressBookCopyArrayOfAllPeople(addressBook);
        NSUInteger i = 0;
        for (i = 0; i < [allContacts count]; i++)
        {
            Person *person = [[Person alloc] init];
            
            ABRecordRef contactPerson = (__bridge ABRecordRef)allContacts[i];
            NSString *firstName = (__bridge_transfer NSString
                                   *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
            NSString *lastName =  (__bridge_transfer NSString
                                   *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
            NSString *fullName = [NSString stringWithFormat:@"%@ %@",
                                  firstName, lastName];
            
            person.firstName = firstName;
            person.lastName = lastName;
            person.fullName = fullName;
            
            //email
            ABMultiValueRef emails = ABRecordCopyValue(contactPerson,kABPersonPhoneProperty);
            NSUInteger j = 0;
            for (j = 0; j < ABMultiValueGetCount(emails); j++)
            {
                NSString *email = (__bridge_transfer NSString
                                   *)ABMultiValueCopyValueAtIndex(emails, j);
                if (j == 0)
                {                     
                    person.homeEmail = email;                 
                    NSLog(@"person.homeEmail = %@ ", person.homeEmail);                 
                }                              
                else if (j==1)                     
                    person.workEmail = email;
            }           
            
            [contactArray addObject:person];
        }     
    }          
    
    CFRelease(addressBook);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSArray *unsortedKeys = [self.contactAlphabeta allKeys];
    NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    
    NSString *key = [sortedKeys objectAtIndex:section];
    NSArray *contactForSection = [self.contactAlphabeta objectForKey:key];
    return [contactForSection count];
}

- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index{
    return 1;
}

- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath{
    //Person *person = [contactArray objectAtIndex:indexPath.row];
    
//    ContactViewController *contactViewController = [[ContactViewController
//                                                     alloc] initWithPerson:person];
//    [self.navigationController pushViewController:contactViewController
//                                         animated:YES];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIdentifer = @"ContactCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
    
    if(cell == nil){
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifer];
    }
    
    NSArray *unsortedKeys = [self.contactAlphabeta allKeys];
    NSArray *sortedKeys = [unsortedKeys sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSString *key = [sortedKeys objectAtIndex:[indexPath section]];
    NSArray *contactForSection = [self.contactAlphabeta objectForKey:key];
    Person *person = [contactForSection objectAtIndex:[indexPath row]];
    cell.textLabel.text = person.fullName;

    return cell;
}


- (NSDictionary *)alphabetizeContacts:(NSMutableArray *)contactList{
    NSMutableDictionary *buffer = [[NSMutableDictionary alloc] init];
    // Put Fruits in Sections
    for (int i = 0; i < [contactList count]; i++) {
        Person *contact = [contactList objectAtIndex:i];
        NSString *firstLetter = [[contact.fullName substringToIndex:1] uppercaseString];
        if ([buffer objectForKey:firstLetter]) {
            [(NSMutableArray *)[buffer objectForKey:firstLetter] addObject:contact];
        } else {
            NSMutableArray *mutableArray = [[NSMutableArray alloc] initWithObjects:contact, nil];
            [buffer setObject:mutableArray forKey:firstLetter];
        }
    }
    // Sort Fruits
    NSArray *keys = [buffer allKeys];
    for (int j = 0; j < [keys count]; j++) {
        NSString *key = [keys objectAtIndex:j];
        [(NSMutableArray *)[buffer objectForKey:key] sortedArrayUsingComparator:^(Person *p1,Person *p2){
            return [p1.fullName caseInsensitiveCompare:p2.fullName];
        }];
    }
    NSDictionary *result = [NSDictionary dictionaryWithDictionary:buffer];
    return result;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    NSArray *keys = [self.contactAlphabeta allKeys];
    return [keys count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    NSArray *keys = [[self.contactAlphabeta allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
    NSString *key = [keys objectAtIndex:section];
    return key;
}


@end
